package com.taptech.doufu.alipay;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import com.alipay.sdk.app.PayTask;
import com.taptech.doufu.event.EventBusPayResult;
import com.taptech.doufu.net.retrofit.RxBus;
import com.taptech.doufu.util.NotifyUtil;
import com.tencent.mm.opensdk.modelbase.BaseResp;

import java.util.Map;

public class AliPayActivity extends AppCompatActivity {
	private static final int SDK_PAY_FLAG = 1;
	private static final String INTENT_KEY_ORDER_INFO = "order_info";

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		@SuppressWarnings("unused")
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				@SuppressWarnings("unchecked")
				PayResult payResult = new PayResult((Map<String, String>) msg.obj);
				/**
				 * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
				 */
				String resultInfo = payResult.getResult();// 同步返回需要验证的信息
				String resultStatus = payResult.getResultStatus();

				EventBusPayResult eventBusWXPay = new EventBusPayResult();
				eventBusWXPay.setTag(EventBusPayResult.tag);
				// 判断resultStatus 为9000则代表支付成功
				if (TextUtils.equals(resultStatus, "9000")) {
					// 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
					NotifyUtil.successPay();
					eventBusWXPay.setSuccess(true);
					eventBusWXPay.setMsg("充值成功");
				} else {
					// 该笔订单真实的支付结果，需要依赖服务端的异步通知。
					NotifyUtil.errorPay(payResult.getMemo());
					eventBusWXPay.setSuccess(false);
					eventBusWXPay.setMsg(payResult.getMemo());
				}
				RxBus.getDefault().post(eventBusWXPay);
				finish();
				break;
			}
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		String orderInfo = getIntent().getStringExtra(INTENT_KEY_ORDER_INFO);
		if (!TextUtils.isEmpty(orderInfo)) {
			pay(orderInfo);
		}else{
			finish();
		}

	}

	/**
	 * 支付宝支付业务
	 */
	public void pay(final String orderInfo) {
		final Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				PayTask alipay = new PayTask(AliPayActivity.this);
				Map<String, String> result = alipay.payV2(orderInfo, true);
				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}




	public static void startActivity(Context context,String orderInfo) {
		Intent intent = new Intent();
		intent.setClass(context, AliPayActivity.class);
		intent.putExtra(INTENT_KEY_ORDER_INFO, orderInfo);
		context.startActivity(intent);
	}

}
